/**  
 * <p> ShaUtil.java</p>
 * <p> com.xikang.ch.cloudweix.utils</p> 
 * <p> 2016年5月18日 下午1:34:09 </p>
 * <p>Copyright：东软熙康健康科技有限公司 2016 </p>
 * @author wdp
 */ 
package com.ylkj.wx.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**  
 * <p>TODO</p>
 * @author <a href=wang_dp@neusoft.com>wdp</a>
 * @version 1.0.0
 * @since  1.0.0
 */
public class ShaUtil {
	public static void main(String[] args) throws NoSuchAlgorithmException,
			UnsupportedEncodingException {
		
		//https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
		String jsapi_ticket = "sM4AOVdWfPE4DxkXGEs8VD8jBGW3-EB6mmivFNLout81rLVu-V1MH4Ii5hA98FClhwq8lYNnINp1bu21j59AXw";
		long timestamp = 1463540486;
		String nonce = "2nDgiWM7gCxhL8v0";
		String jsurl = "http://www.xikang365.net/wx/page/index/";
		System.out.println(getJsapiTicket(jsapi_ticket, timestamp, nonce, jsurl));
	}
	
	public static String getJsapiTicket(String jsapiTicket, long timestamp, String nonce, String jsurl) throws NoSuchAlgorithmException{
		String[] paramArr = new String[] { "jsapi_ticket=" + jsapiTicket,
				"timestamp=" + timestamp, "noncestr=" + nonce, "url=" + jsurl };
		Arrays.sort(paramArr);
		// 将排序后的结果拼接成一个字符串
		String content = paramArr[0].concat("&" + paramArr[1])
				.concat("&" + paramArr[2]).concat("&" + paramArr[3]);
		MessageDigest md = MessageDigest.getInstance("SHA-1");
		// 对接后的字符串进行sha1加密
		byte[] digest = md.digest(content.toString().getBytes());
		String reslut = byteToStr(digest);
		return reslut;
	}
	
	/**
	 * 将字节数组转换为十六进制字符串
	 * 
	 * @param byteArray
	 * @return
	 */
	private static String byteToStr(byte[] byteArray) {
		String strDigest = "";
		for (int i = 0; i < byteArray.length; i++) {
			strDigest += byteToHexStr(byteArray[i]);
		}
		return strDigest;
	}

	/**
	 * 将字节转换为十六进制字符串
	 * 
	 * @param mByte
	 * @return
	 */
	private static String byteToHexStr(byte mByte) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
		tempArr[1] = Digit[mByte & 0X0F];

		String s = new String(tempArr);
		return s;
	}
}
